﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WarehouseInsp.Buz.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.WarehouseInsp.Buz.DataAccess;
using Microhard.WarehouseInsp.Buz.DTO;
using Microhard.WarehouseInsp.Buz.Msg;
using Microhard.Core;
using Microhard.WarehouseInsp.Buz.BuzEnum;
using Microhard.WarehouseInsp.Buz.Models;

namespace Microhard.WarehouseInsp.Buz.Impls
{
    public class PledgePlanInRecordsImpl : IPledgePlanInRecords
    {
        public Core.DBUtility.ExecutedResult Add(Models.PledgePlanInRecordsModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var op = model.ToEntity();
            //通过产品名称寻找配置库中是否存在
            var prd = db.ProductLists.SingleOrDefault(p => p.Name == model.ProductIDForSelect);
            if (prd == null)
            {
                prd = new ProductList
                {
                    CreateTime = DateTime.Now,
                    Name = model.ProductIDForSelect,
                    ProductID = Guid.NewGuid()
                };
                db.ProductLists.AddObject(prd);
            }
            op.ProductID = prd.ProductID;
            op.WarehouseID = Guid.Parse(model.WarehouseIDForSelect);
            op.CreateTime = DateTime.Now;
            if (model.PlanAmount > 0)
            {
                op.PlanAmount = model.PlanAmount;
            }
            else
            {
                op.PlanAmount = (decimal)op.PlanCount.Value * op.PlanPrice.Value;
            }
            op.Status = (int)PrjStatus.Saved;

            try
            {
                db.PledgePlanInRecords.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, PledgePlanInRecordsMsg.AddFailed);
                Log.Error("IPledgePlanInRecords.Add", ex);
            }
            return rtn;
        }

        public Core.DBUtility.ExecutedResult Update(Models.PledgePlanInRecordsModel model)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.PledgePlanInRecords.SingleOrDefault(l => l.PlnPdgID == model.PlnPdgID &&
                (l.Status == (int)PrjStatus.RollBack || l.Status == (int)PrjStatus.Saved));
            if (entity != null)
            {
                entity.PlanCount = model.PlanCount;
                entity.PlanPrice = model.PlanPrice;
                Guid warehouseIdForSelect = Guid.Empty;
                if (Guid.TryParse(model.WarehouseIDForSelect, out warehouseIdForSelect))
                {
                    entity.WarehouseID = warehouseIdForSelect;
                }
                //Guid productIDForSelect = Guid.Empty;
                //if (Guid.TryParse(model.ProductIDForSelect, out productIDForSelect))
                //{
                //    entity.ProductID = productIDForSelect;
                //}
                if (model.PlanAmount > 0)
                {
                    entity.PlanAmount = model.PlanAmount;
                }
                else
                {
                    entity.PlanAmount = (decimal)entity.PlanCount.Value * entity.PlanPrice.Value;
                }
                entity.PlgCategory = model.PlgCategory;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, PledgePlanInRecordsMsg.UpdateFailed);
                Log.Error("IPledgePlanInRecords.Update", ex);
            }
            return result;
        }

        public Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var toDelete = db.PledgePlanInRecords.Where(e => ids.Contains(e.PlnPdgID)).ToList();
            toDelete.ForEach(e =>
            {
                //质押物是否在使用
                if (e.Status == (int)PrjStatus.RollBack || e.Status == (int)PrjStatus.Saved)
                {
                    db.PledgePlanInRecords.DeleteObject(e);
                }
                else
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(PledgePlanInRecordsMsg.IsInUsing, e.ProductList.Name));
                }
            });
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, PledgePlanInRecordsMsg.DeleteFailed);
                    Log.Error("IPledgePlanInRecords.Delete", ex);
                }
            }
            return result;
        }

        public Core.DBUtility.ExecutedResult Delete(Models.PledgePlanInRecordsModel model)
        {
            throw new NotImplementedException();
        }

        public Models.PledgePlanInRecordsModel GetModelByID(Guid id)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.PledgePlanInRecords.SingleOrDefault(e => e.PlnPdgID == id);
            if (entity != null)
            {
                return entity.ToModel();
            }
            return null;
        }

        public Models.PledgePlanInRecordsModel GetModelByModel(Models.PledgePlanInRecordsModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.PledgePlanInRecordsModel> Query(Models.PledgePlanInRecordsModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            IEnumerable<PledgePlanInRecord> entities = from b in db.PledgePlanInRecords
                                                       where b.ProjectID == Model.ProjectID
                                                       select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<PledgePlanInRecordsModel>();
        }

        public List<Models.PledgePlanInRecordsModel> Query(Models.PledgePlanInRecordsModel Model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            IEnumerable<PledgePlanInRecord> entities = from b in db.PledgePlanInRecords
                                                       where b.ProjectID == Model.ProjectID
                                                       select b;
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<PledgePlanInRecordsModel>();
        }

        public Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }

        public List<PledgePlanInRecordsModel> GetPlanPlgsByUserID(PledgePlanInRecordsModel model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            IEnumerable<PledgePlanInRecord> entities = from b in db.PledgePlanInRecords
                                                       where (b.SupProject.PMID == this.scope.CurrentUserID
                                                       || b.Warehouse.WarehouseMngID == this.scope.CurrentUserID
                                                       || b.SupProject.ProtalEmpID == this.scope.CurrentUserID)
                                                       && b.Status == (int)PrjStatus.Finished
                                                       select b;
            if (!string.IsNullOrEmpty(model.QueryForProductName))
            {
                entities = from e in entities
                           where e.ProductList.Name.IndexOf(model.QueryForProductName) > -1
                           select e;
            }
            if (!string.IsNullOrEmpty(model.QueryForPrjCode))
            {
                entities = from e in entities
                           where e.SupProject.Code == model.QueryForPrjCode
                           select e;
            }
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
                return pagedEntities.Select(m => m.ToModel()).ToList();
            return new List<PledgePlanInRecordsModel>();
        }


        public bool HasAddPlg(Guid prjID, string plgName)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var cnt = db.PledgePlanInRecords.Count(c => c.SupProject.ProjectID == prjID
                && c.ProductList.Name == plgName);
            return cnt > 0 ? true : false;
        }
    }
}
